import Vue from 'vue'
import Router from 'vue-router'
import storage from 'store'
import store from '@/store/index'
import { treeDataTranslate } from '@/util/index'

Vue.use(Router)

const globalRoutes = [{
    path: '/login',
    component: () => import('@/pages/login')
}]

const dynamicRoutes = {
    path: '/',
    component: () => import('@/components/layout'),
    redirect: '/index',
    children: [
        {
            path: '/index',
            component: () => import('@/pages/index'),
        },
    ]
}
const router = new Router({
    mode: 'history',
    routes: globalRoutes,
    isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
})

router.beforeEach((to, from, next) => {
    const token = storage.get('token')
    if (to.path === '/login') {
        next()
    } else {
        if (token) {
            store.dispatch('authorization/AUTHORIZATION').then(response => {
                if (router.options.isAddDynamicMenuRoutes) {
                    next()
                } else {
                    const menuList = treeDataTranslate(store.state.authorization.resources.filter(resource => resource.type < 2))
                    fnAddDynamicMenuRoutes(menuList)
                    router.options.isAddDynamicMenuRoutes = true
                    next({ ...to, replace: true })
                }
            }).catch(error => {
                next('/login')
            })
        } else {
            next('/login')
        }
    }
})


/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
    var temp = []
    for (var i = 0; i < menuList.length; i++) {
        if (menuList[i].children && menuList[i].children.length >= 1) {
            temp = temp.concat(menuList[i].children)
        } else {
            var route = {
                path: menuList[i].url,
                component: getViews(menuList[i].url),
                name: menuList[i].url,
            }
            routes.push(route)
        }
    }
    if (temp.length >= 1) {
        fnAddDynamicMenuRoutes(temp, routes)
    } else {
        routes.forEach(route => {
            dynamicRoutes.children.push(route)
        });
        router.options.routes.push(dynamicRoutes)
        router.addRoutes([dynamicRoutes])
    }
}

function getViews(path) {
    return () => import(`@/pages${path}.vue`)
}
export default router